package com.excesys.exsecs.om.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.excesys.exsecs.common.core.util.R;
import com.excesys.exsecs.common.security.service.ExsecsUser;
import com.excesys.exsecs.common.security.util.SecurityUtils;
import com.excesys.exsecs.om.constans.OmCommonConstants;
import com.excesys.exsecs.om.dto.*;
import com.excesys.exsecs.om.entity.*;
import com.excesys.exsecs.om.mapper.*;
import com.excesys.exsecs.om.service.*;
import com.excesys.exsecs.om.utils.DateUtils;
import com.excesys.exsecs.om.utils.OrderNoUtils;
import com.excesys.exsecs.om.vo.ResutlVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/omregionalItems")
@Tag(name = "巡查区域事项")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class OmRegionalInspectionItemsController {

	private final OmDeviceModelClassificationMapper omDeviceModelClassificationMapper;

	private final OmEventAndRegionService omEventAndRegionService;

	private final OmInspectionResultService omInspectionResultService;

	private final OmInspectionResultMapper omInspectionResultMapper;

	private final OmDeviceModelClassificationService omDeviceModelClassificationService;

	private final OmICheckPointService omICheckPointService;

	private final OmInspectionPhotoService omInspectionPhotoService;

	private final SequenceMapper sequenceMapper;

	private final OrderNoUtils orderNoUtils;

	private final OmWOrderHistoryMapper omWOrderHistoryMapper;

	private final OmWOrderMapper omWOrderMapper;

	private final OmEvenAndFacilityMapper omEvenAndFacilityMapper;

	private final OmInspectionItemsMapper omInspectionItemsMapper;

	private final OmWOrderFileMapper omWOrderFileMapper;

	private final OmICheckSheetMapper omICheckSheetMapper;

	/**
	 * 根据点位获取区域id
	 */
	@Operation(summary = "通过点位查询区域id", description = "通过点位查询区域id")
	@GetMapping("/getInspectionId/{exId}")
	public R getInspectionId(@PathVariable("exId") String exId) {
		OmICheckPoint omICheckPoint = omICheckPointService.getById(exId);
		return R.ok(omICheckPoint.getAreaNo());

	}

	/**
	 * 通过id查询巡检区域列表
	 * @param exId id
	 * @return R
	 */
	@Operation(summary = "通过区域id查询", description = "通过区域id查询")
	@GetMapping("/{exId}")
	// @PreAuthorize("@pms.hasPermission('om_equipmentIdList_get')" )
	public R getById(@PathVariable("exId") String exId) {
		List<String> list = new ArrayList<>();
		List<OmInspectionItems> items = new ArrayList<>();
		List<OmEvenAndFacility> facilities = omEvenAndFacilityMapper.getfacityList(exId);
		for (OmEvenAndFacility omEvenAndFacility : facilities) {
			list.add(omEvenAndFacility.getItemsId());
		}
		for (int i = 0; i < list.size(); i++) {
			if (ObjectUtil.isNotEmpty(omInspectionItemsMapper.getItemsByIds(list.get(i)))) {
				items.add(omInspectionItemsMapper.getItemsByIds(list.get(i)));
			}
		}
		return R.ok(items);
	}

	/**
	 * 通过id查询设备巡检项列表
	 * @param exId id
	 * @return R
	 */
	@Operation(summary = "通过区域id查询", description = "通过区域id查询")
	@GetMapping("getEquipmentById/{exId}")
	// @PreAuthorize("@pms.hasPermission('om_equipmentIdList_get')" )
	public R getEquipmentById(@PathVariable("exId") String exId) {
		List<DeviceQueryResp> list = omDeviceModelClassificationService.getIdList(exId);
		return R.ok(list);
	}

	/**
	 * 通过设备id查询巡检项列表
	 * @param exId id
	 * @return R
	 */
	@Operation(summary = "通过设备id查询巡检项列表", description = "通过设备id查询巡检项列表")
	@GetMapping("getEquipmentItemsById/{exId}")
	// @PreAuthorize("@pms.hasPermission('om_equipmentIdList_get')" )
	public R getEquipmentItemsById(@PathVariable("exId") String exId) {
		List<OmInspectionItems> list = omDeviceModelClassificationService.getItemsList(exId);
		return R.ok(list);
	}

	/**
	 * 存储巡检记录
	 * @return R
	 */
	@Operation(summary = "存储巡检记录", description = "存储巡检记录")
	@PostMapping
	// @PreAuthorize("@pms.hasPermission('om_equipmentIdList_save')" )
	public R saveValue(@RequestBody ValueDto valueDto) {
		log.info("valueDto:" + valueDto);
		String flag = "";
		OmICheckSheet omICheckSheet = omICheckSheetMapper.getSheetByCheckNo(valueDto.getInspectionSheetId());
		if (valueDto.getInspectionDtolist().size() <= 0) {
			if ("1".equals(valueDto.getCategory())) {
				OmInspectionResult or = omInspectionResultService.getOmInspectionResultList(valueDto.getPointCode(),
						valueDto.getInspectionSheetId());
				or.setInspectionSheetId(valueDto.getInspectionSheetId());
				or.setPointCode(valueDto.getPointCode());
				or.setInspectionAreaClassification(valueDto.getInspectionAreaClassification());
				or.setIrId(valueDto.getIrId());
				or.setRouteName(valueDto.getRouteName());
				if (ObjectUtil.isEmpty(omICheckSheet))
					or.setCheckUserName("");
				else
					or.setCheckUserName(omICheckSheet.getCheckUserName());
				if (StringUtil.isNotEmpty(valueDto.getRemarks()))
					or.setRemarks(valueDto.getRemarks());
				else
					or.setRemarks("");
				if (StringUtil.isNotEmpty(valueDto.getEquipmentStatus()))
					or.setEquipmentStatus(valueDto.getEquipmentStatus());
				else
					or.setEquipmentStatus("");
				or.setFlag("1");
				log.info("or:" + or);
				omInspectionResultService.updateById(or);
			}
			else if ("0".equals(valueDto.getCategory())) {
				OmInspectionResult or = new OmInspectionResult();
				or.setInspectionSheetId(valueDto.getInspectionSheetId());
				or.setPointCode(valueDto.getPointCode());
				or.setInspectionAreaClassification(valueDto.getInspectionAreaClassification());
				if (StringUtil.isNotEmpty(valueDto.getRemarks()))
					or.setRemarks(valueDto.getRemarks());
				else
					or.setRemarks("");
				if (StringUtil.isNotEmpty(valueDto.getEquipmentStatus()))
					or.setEquipmentStatus(valueDto.getEquipmentStatus());
				else
					or.setEquipmentStatus("");
				or.setFlag("1");
				or.setIrId(valueDto.getIrId());
				or.setRouteName(valueDto.getRouteName());
				if (ObjectUtil.isEmpty(omICheckSheet))
					or.setCheckUserName("");
				else
					or.setCheckUserName(omICheckSheet.getCheckUserName());
				OmInspectionResult omInspectionResult = omInspectionResultService.getResult(
						valueDto.getInspectionAreaClassification(), valueDto.getPointCode(),
						valueDto.getInspectionSheetId());
				if (ObjectUtil.isNotEmpty(omInspectionResult)) {
					omInspectionResult.setRemarks(or.getRemarks());
					omInspectionResultService.updateById(omInspectionResult);
				}
				else {
					omInspectionResultService.save(or);
				}
			}
		}
		else {
			for (InspectionDto ip : valueDto.getInspectionDtolist()) {
				// 设备
				if ("0".equals(valueDto.getCategory())) {
					OmInspectionResult or = new OmInspectionResult();
					or.setInspectionAreaClassification(valueDto.getInspectionAreaClassification());
					or.setPointCode(valueDto.getPointCode());
					or.setInspectionSheetId(valueDto.getInspectionSheetId());
					or.setInspectionValue("1");
					or.setEquipmentStatus("0");
					if ("0".equals(ip.getInspectionValue())) {
						// 异常巡检
						or.setEquipmentStatus("1");
						or.setInspectionValue("0");
						flag = "1";
					}
					or.setFlag("1");
					if (StringUtil.isNotEmpty(valueDto.getRemarks()))
						or.setRemarks(valueDto.getRemarks());
					else
						or.setRemarks("");
					or.setIrId(valueDto.getIrId());
					or.setRouteName(valueDto.getRouteName());
					if (ObjectUtil.isEmpty(omICheckSheet))
						or.setCheckUserName("");
					else
						or.setCheckUserName(omICheckSheet.getCheckUserName());
					if (ObjectUtil
							.isNotEmpty(omInspectionResultService.getResult(valueDto.getInspectionAreaClassification(),
									valueDto.getPointCode(), valueDto.getInspectionSheetId()))) {
						OmInspectionResult omInspectionResult1 = omInspectionResultService.getResult(
								valueDto.getInspectionAreaClassification(), valueDto.getPointCode(),
								valueDto.getInspectionSheetId());
						log.info("omInspectionResult1:{}" + omInspectionResult1);
						String[] values = omInspectionResult1.getInspectionId().split(",");
						String newValues = "";
						String mark = "0";
						for (int i = 0; i < values.length; i++) {
							if (values[i].contains(ip.getInspectionId())) {
								values[i] = values[i].substring(0, values[i].length() - 1) + ip.getInspectionValue();
								mark = "1";
							}
							newValues = newValues + "," + values[i];
						}
						if ("1".equals(mark)) {
							omInspectionResult1.setInspectionId(newValues.replaceFirst(",", ""));
						}
						else {
							omInspectionResult1.setInspectionId(omInspectionResult1.getInspectionId() + ","
									+ (ip.getInspectionId() + "-" + ip.getInspectionValue()));
						}
						omInspectionResultService.updateById(omInspectionResult1);
					}
					else {
						or.setInspectionId(ip.getInspectionId() + "-" + ip.getInspectionValue());
						omInspectionResultService.saveOrUpdate(or);
					}
				}
				else if ("1".equals(valueDto.getCategory())) {
					OmInspectionResult omInspectionResult = omInspectionResultService
							.getOmInspectionResultList(valueDto.getPointCode(), valueDto.getInspectionSheetId());
					log.info("打印omInspectionResult:{}" + omInspectionResult);
					if (ObjectUtil.isNotEmpty(omInspectionResult)) {
						// 区域巡检项
						if (StringUtil.isNotEmpty(omInspectionResult.getNfcTime())) {
							if (!omInspectionResult.getInspectionId().contains(ip.getInspectionId())) {
								if (StringUtil.isEmpty(omInspectionResult.getInspectionId())) {
									omInspectionResult
											.setInspectionId(ip.getInspectionId() + "-" + ip.getInspectionValue());
								}
								else {
									omInspectionResult.setInspectionId(omInspectionResult.getInspectionId() + ","
											+ (ip.getInspectionId() + "-" + ip.getInspectionValue()));
								}

							}
							else {
								String[] values = omInspectionResult.getInspectionId().split(",");
								String newValues = "";
								String mark = "0";
								for (int i = 0; i < values.length; i++) {
									if (values[i].contains(ip.getInspectionId())) {
										values[i] = values[i].substring(0, values[i].length() - 1)
												+ ip.getInspectionValue();
										mark = "1";
									}
									newValues = newValues + "," + values[i];
								}
								if ("1".equals(mark)) {
									omInspectionResult.setInspectionId(newValues.replaceFirst(",", ""));
								}
								else {
									omInspectionResult.setInspectionId(omInspectionResult.getInspectionId() + ","
											+ (ip.getInspectionId() + "-" + ip.getInspectionValue()));
								}
							}
							omInspectionResult.setInspectionValue("1");
							omInspectionResult.setEquipmentStatus("0");
							if ("0".equals(ip.getInspectionValue())) {
								// 异常巡检
								omInspectionResult.setEquipmentStatus("1");
								omInspectionResult.setInspectionValue("0");
								flag = "1";
							}
							if (StringUtil.isNotEmpty(valueDto.getRemarks()))
								omInspectionResult.setRemarks(valueDto.getRemarks());
							else
								omInspectionResult.setRemarks("");
							omInspectionResult.setFlag("1");
							omInspectionResult
									.setInspectionAreaClassification(valueDto.getInspectionAreaClassification());
							omInspectionResultService.saveOrUpdate(omInspectionResult);
						}
					}
				}
			}
		}

		if (valueDto.getFileList().size() > 0) {
			for (FileDto fileDto : valueDto.getFileList()) {
				OmInspectionPhoto omInspectionPhoto = new OmInspectionPhoto();
				omInspectionPhoto.setPointCode(valueDto.getPointCode());
				omInspectionPhoto.setInspectionSheetId(valueDto.getInspectionSheetId());
				omInspectionPhoto.setInspectionAreaClassification(valueDto.getInspectionAreaClassification());
				omInspectionPhoto.setUrl(fileDto.getUrl());
				omInspectionPhoto.setFileId(fileDto.getFileId());
				List<OmInspectionPhoto> list = omInspectionPhotoService.getResult(
						valueDto.getInspectionAreaClassification(), valueDto.getPointCode(),
						valueDto.getInspectionSheetId(), fileDto.getUrl());
				if (list.size() <= 0)
					omInspectionPhotoService.save(omInspectionPhoto);
			}
		}

		log.info("flag：" + flag);
		// 巡检异常生成工单
		if ("1".equals(flag)) {
			OmWOrder order = new OmWOrder();
			int orderSeq = sequenceMapper.getSeqNextVal("orderseq");
			order.setOrderNo(orderNoUtils.getOrderNumber("Order", orderSeq));
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DateUtils.DATE_FORMATE_STRING_A);
			order.setApplyTime(LocalDateTime.parse(LocalDateTime.now().format(formatter), formatter));
			order.setOrderStatus(OmCommonConstants.ORDER_STATUS_0);// 创建工单时默认待处理状态
			order.setAppointType("1");
			if (StringUtil.isNotEmpty(valueDto.getRemarks()))
				order.setApplyContent(valueDto.getRemarks());
			else
				order.setApplyContent("");
			OmWOrderHistory omWOrderHistory = new OmWOrderHistory();
			omWOrderHistory.setOperation("创建工单");
			ExsecsUser ExsecsUser = SecurityUtils.getUser();
			// 工单报告人信息
			order.setOrderUserDeptId(ExsecsUser.getDeptId());
			order.setOrderUserId(ExsecsUser.getId());
			order.setOrderUserName(ExsecsUser.getName());
			order.setOrderUserPhone(ExsecsUser.getPhone());
			// 指派给部门领班
			order.setHandleUserDeptId(0L);
			order.setHandleUserId(0L);
			// 报修类型
			List<OmDeviceModelClassification> list = omDeviceModelClassificationMapper
					.getItemsList(valueDto.getInspectionAreaClassification());
			if (list.size() > 0) {
				order.setOrderType("0");
				order.setOrderName("设备报修-" + order.getOrderNo());
				order.setEquipNo(valueDto.getInspectionAreaClassification());
			}
			else {
				order.setOrderType("6");
				order.setOrderName("其他-" + order.getOrderNo());
			}

			omWOrderHistory.setOperateUserId(ExsecsUser.getId());
			omWOrderHistory.setOperateDeptId(ExsecsUser.getDeptId());
			omWOrderHistory.setOrderNo(order.getOrderNo());
			omWOrderHistoryMapper.insert(omWOrderHistory);
			if (valueDto.getFileList().size() > 0) {
				for (FileDto dto : valueDto.getFileList()) {
					order.setApplyFile(dto.getUrl());
				}
			}
			if (StringUtil.isNotEmpty(order.getRemark()))
				order.setApplyContent(order.getRemark());
			order.setOrderFrom("1");// 巡检
			omWOrderMapper.insert(order);
			if (valueDto.getFileList().size() > 0) {
				for (FileDto fileDto : valueDto.getFileList()) {
					OmWOrderFile omWOrderFile = new OmWOrderFile();
					omWOrderFile.setOrderNo(order.getOrderNo());
					omWOrderFile.setUrl(fileDto.getUrl());
					omWOrderFile.setFileId(Integer.valueOf(fileDto.getFileId()));
					omWOrderFileMapper.insert(omWOrderFile);
				}
			}
		}

		return R.ok();
	}

	/**
	 * 查询巡检记录
	 * @return R
	 */
	@Operation(summary = "查询巡检记录", description = "查询巡检记录")
	@PostMapping("/getinspectionResultList")
	public R getinspectionResultList(@RequestBody ResultDto resultDto) {
		ValueDto valueDto = omInspectionResultService.getList(resultDto);
		return R.ok(valueDto);
	}

	/**
	 * 查询巡检异常记录
	 * @return R
	 */
	@Operation(summary = "查询巡检异常记录", description = "查询巡检异常记录")
	@GetMapping("/getResultList")
	public R getinspectionResultList(Page page, ResutlVo resultDto) {
		return R.ok(omInspectionResultService.getResultList(page, resultDto));
	}

//	/**
//	 * 导出巡检异常记录
//	 * @return R
//	 */
//	@Operation(summary = "导出巡检异常记录", description = "导出巡检异常记录")
//	@GetMapping("/export")
//	public List<ExceptionVo> export() {
//		return omInspectionResultService.listBamSBuildings();
//	}
}
